
package security.beans;

import Entity.TableModelUser;
import Entity.User;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;
import login.beans.ConectionBean;
import org.primefaces.event.TransferEvent;
import org.primefaces.model.DualListModel;
import security.DAO.UserDAO;
import security.business.RolBusiness;
import security.business.UserBusiness;

/**
 *
 * @author JuanFelipe
 */
@ManagedBean
@ViewScoped
public class UserBean implements Serializable {
    
    private List<User>users;
    private User selectedUser;
    private TableModelUser tableModel;
    private static final long serialVersionUID = 102L;
    private int ntab;
    private Connection  conn;
    private DualListModel< String > privileges;
    private CreateUserBean cub;
    
    public UserBean(  ) {
        FacesContext context = javax.faces.context.FacesContext.getCurrentInstance();
        HttpSession session = (HttpSession) context.getExternalContext().getSession(false);
        ConectionBean conectionBean =(ConectionBean) session.getAttribute("conectionBean");
        conn = conectionBean.currentConnection; 
        cub = new CreateUserBean();
        init( conn );
    }
    
    public void init( Connection conn ) {
        ntab = 0;
        selectedUser = new User();
        try {
            users = new UserBusiness( conn ).getUsers();
            tableModel = new TableModelUser( users );
        } catch (SQLException ex) {
            FacesContext.getCurrentInstance().addMessage(
                    null,
                    new FacesMessage(FacesMessage.SEVERITY_WARN,
                    "Please Try Again!",
                    ex.getMessage()));
        }
        
        
    }
    
    public List<User> getUsers() {
        return users;
    }

    public void setUsers(List<User> users) {
        this.users = users;
    }

    public int getNtab() {
        return ntab;
    }

    public void setNtab(int ntab) {
        this.ntab = ntab;
    }

    public User getSelectedUser() {
        return selectedUser;
    }

    public void setSelectedUser(User selectedUser) {
        this.selectedUser = selectedUser;
    }

    public TableModelUser getTableModel() {
        return tableModel;
    }

    public void setTableModel(TableModelUser tableModel) {
        this.tableModel = tableModel;
    }

    public DualListModel<String> getPrivileges() {
        return privileges;
    }

    public void setPrivileges(DualListModel<String> privileges) {
        this.privileges = privileges;
    }

    public CreateUserBean getCub() {
        return cub;
    }

    public void setCub(CreateUserBean cub) {
        this.cub = cub;
    }
    
    
    public void edit() {  
        FacesMessage msg;
        System.out.print("EDIT!!!!! >>>");
        
        ntab = 2;
        
        msg = new FacesMessage("Puede Editar!", "Usuario: "+selectedUser.getName());  
        chargeData();
        msg.setSeverity(FacesMessage.SEVERITY_INFO);
        FacesContext.getCurrentInstance().addMessage(null, msg); 
        
    }  
    
    private void chargeData() {
        List< String > privSource = new CreateRolBean().initPrivileges();
        List< String > privTarget = getPrivRol(selectedUser.getName() );
        System.out.println("PRIV TARGET");
        for( String s: privTarget ){
            System.out.println(" PT->> "+s);
            privSource.remove( s );
        }
        
        privileges = new DualListModel<>(privSource, privTarget);
    }
    
    private List<String> getPrivRol(String name) {
        FacesMessage msg = new FacesMessage();  
          
        ArrayList<String> res = new ArrayList<>();
        try {
            
            res = new RolBusiness( conn ).getPrivileges( name );
            
            msg.setSeverity(FacesMessage.SEVERITY_INFO);  
            //msg.setSummary("Privilegios");
            //msg.setDetail("Mostrados Exitosamente");  
            //FacesContext.getCurrentInstance().addMessage(null, msg);  
            return res;
        } catch (SQLException ex) {
            msg.setSeverity(FacesMessage.SEVERITY_ERROR);  
            msg.setSummary("ERROR!");
            msg.setDetail("Fallo al cargar privilegios "+ex);  
            FacesContext.getCurrentInstance().addMessage(null, msg);  
        }
        return res;
    }
    
    
    public void onTransfer(TransferEvent event) {  
        StringBuilder builder = new StringBuilder();  
        RolBusiness rb = new RolBusiness( conn );
        FacesMessage msg = new FacesMessage();  
        
        for(Object item : event.getItems()) {  
            //System.out.println("OnTRansfer: "+ (String) item);
            if( privileges.getTarget().contains((String) item) ){
                try {
                    rb.addPrivileges( (String) item, selectedUser.getName() );
                    builder.append( (String) item );
                } catch (SQLException ex) {
                    msg = new FacesMessage();  
                    msg.setSeverity(FacesMessage.SEVERITY_FATAL);  
                    msg.setSummary("Error al asignar Privilegio");
                    msg.setDetail("Privilegio: "+item + " " + ex.getMessage());  

                    FacesContext.getCurrentInstance().addMessage(null, msg);  
                }
            }else {
                try {
                    rb.revokePrivileges( (String) item, selectedUser.getName());
                    builder.append( (String) item );
                } catch (SQLException ex) {
                    msg = new FacesMessage();  
                    msg.setSeverity(FacesMessage.SEVERITY_FATAL);  
                    msg.setSummary("Error al revocar Privilegio");
                    msg.setDetail("Privilegio: "+item + " " + ex.getMessage());  

                    FacesContext.getCurrentInstance().addMessage(null, msg);  
                }
            }
        }
        
        msg = new FacesMessage();  
        msg.setSeverity(FacesMessage.SEVERITY_INFO);  
        msg.setSummary("Items Transferidos:");
        msg.setDetail(builder.toString());  
          
        FacesContext.getCurrentInstance().addMessage(null, msg);
    }
    
    public void delete( ){
        FacesMessage msg = new FacesMessage();  
        
        if( selectedUser!=null && !selectedUser.getName().equals("") ){
            
            System.out.println("ACA");
            System.out.println("NAME: "+ ( (selectedUser!=null)? selectedUser.getName():"NULL") );
            
            UserDAO ub = new UserDAO( conn );
            try {
                //Elimina en cascada
                ub.dropUser(selectedUser.getName() , true);
                
                msg.setSeverity(FacesMessage.SEVERITY_INFO);  
                msg.setSummary("Usuario Eliminado");
                msg.setDetail("Usuario eliminado Exitosamente");  
                
                users.remove( selectedUser );
                tableModel = new TableModelUser( users );
                selectedUser = null;
                FacesContext.getCurrentInstance().addMessage(null, msg);  
            } catch (SQLException ex) {
                msg.setSeverity(FacesMessage.SEVERITY_ERROR);  
                msg.setSummary("Error al eliminar");
                msg.setDetail("El Ususario no pudo ser eliminado "+ ex.getMessage() );  
            }
            
            selectedUser = null;
        }
    }
    
    
}
